<template>
  <div class="list-container">
    <AdminDialog
      v-model:visible="dialogVisible"
      :isEdit="dialogMode === 'edit'"
      :adminId="editId"
      :adminData="editData"
      @success="handleDialogSuccess"
    />
    <PasswordDialog
      v-model:visible="pwdDialogVisible"
      :adminId="pwdEditId"
      @success="handlePasswordSuccess"
    />
    <!-- 搜索和操作栏 -->
    <div class="list-header">
      <div class="search-form">
        <div class="search-form-item">
          <label>管理员名称</label>
          <el-input
            v-model="searchForm.username"
            placeholder="请输入管理员名称"
            clearable
            @keyup.enter="handleSearch"
          />
        </div>
        <div class="search-form-item">
          <label>管理员邮箱</label>
          <el-input
            v-model="searchForm.email"
            placeholder="请输入管理员邮箱"
            clearable
            @keyup.enter="handleSearch"
          />
        </div>
        <div class="search-form-item">
          <label>管理员角色</label>
          <el-select
            v-model="searchForm.role"
            placeholder="请选择角色"
            clearable
            @change="handleSearch"
          >
            <el-option label="超级管理员" value="1" />
            <el-option label="商品管理员" value="2" />
            <el-option label="数据分析员" value="3" />
          </el-select>
        </div>
      </div>
      <div class="search-actions">
        <el-button type="primary" @click="handleSearch">
          <el-icon><Search /></el-icon>
          搜索
        </el-button>
        <el-button @click="handleReset">
          <el-icon><RefreshRight /></el-icon>
          重置
        </el-button>
        <el-button type="success" @click="handleAdd">
          <el-icon><Plus /></el-icon>
          新增管理员
        </el-button>
      </div>
    </div>

    <!-- 表格内容 -->
    <div class="list-content">
      <div class="list-table" v-loading="loading">
        <div class="table-scroll-wrapper" ref="tableScroll">
          <el-table
            :data="adminList"
            stripe
            style="width: 100%"
            :default-sort="{ prop: 'addTime', order: 'descending' }"
          >
          <el-table-column type="index" label="序号" width="60" align="center" />
          <el-table-column prop="uid" label="UID" width="80" align="center" />
          <el-table-column prop="username" label="用户名" min-width="120" show-overflow-tooltip />
          <el-table-column prop="email" label="邮箱" min-width="150" show-overflow-tooltip />
          <el-table-column prop="role" label="角色" min-width="100" align="center" show-overflow-tooltip>
            <template #default="{ row }">
              <el-tag :type="getRoleType(row.role)">{{ getRoleLabel(row.role) }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="enable" label="状态" min-width="100" align="center">
            <template #default="{ row }">
              <el-tag :type="row.enable === 1 ? 'success' : 'danger'">
                {{ row.enable === 1 ? '启用' : '禁用' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column
            prop="addTime"
            label="创建时间"
            min-width="180"
            sortable
            show-overflow-tooltip
            :formatter="(row) => formatDateTime(row.addTime)"
          />
          <el-table-column
            prop="updateTime"
            label="更新时间"
            min-width="180"
            show-overflow-tooltip
            :formatter="(row) => formatDateTime(row.updateTime)"
          />
          <el-table-column label="操作" min-width="260" align="center" fixed="right">
            <template #default="{ row }">
              <div class="action-buttons">
                <el-button type="primary" size="small" @click="handleEdit(row)">
                  编辑
                </el-button>
                <el-button type="warning" size="small" @click="handleChangePassword(row)">
                  修改密码
                </el-button>
                <el-button type="danger" size="small" @click="handleDelete(row)">
                  删除
                </el-button>
              </div>
            </template>
          </el-table-column>
          </el-table>
        </div>

        <!-- 水平滑动进度条（当表格宽度超出容器时显示） -->
        <input
          v-show="showHScroll"
          ref="hSlider"
          class="horizontal-scroll"
          type="range"
          min="0"
          max="100"
          :value="hScrollPercent"
          @input="onSliderInput"
        />
      </div>
    </div>

    <!-- 分页 -->
    <div class="list-footer">
      <el-pagination
        v-model:current-page="pagination.currentPage"
        v-model:page-size="pagination.pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :total="pagination.total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, onBeforeUnmount } from 'vue'
import AdminDialog from './dialogs/AdminDialog.vue'
import PasswordDialog from './dialogs/PasswordDialog.vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, RefreshRight, Plus } from '@element-plus/icons-vue'

import '@/assets/css/table-list.css'
import {
  getAllAdmins,
  getAdminById,
  addAdmin,
  updateAdmin,
  deleteAdmin,
  searchAdmins
} from '@/api/admin'
import { changeAdminPassword } from '@/api/admin'

// 搜索表单
const searchForm = reactive({
  username: '',
  email: '',
  role: ''
})

// 管理员列表数据
const adminList = ref([])

// 分页参数
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 加载状态
const loading = ref(false)

// 格式化日期时间
const formatDateTime = (dateTime) => {
  if (!dateTime) return 'N/A'
  return dateTime.replace('T', ' ').substring(0, 19)
}

// 获取角色标签
const getRoleLabel = (role) => {
  const roleMap = {
    '1': '超级管理员',
    '2': '商品管理员',
    '3': '数据分析员'
  }
  return roleMap[role] || '未知角色'
}

// 获取角色标签类型
const getRoleType = (role) => {
  const typeMap = {
    '1': 'danger',     // 超级管理员 - 红色
    '2': 'warning',    // 商品管理员 - 黄色
    '3': 'info'        // 数据分析员 - 蓝色
  }
  return typeMap[role] || 'info'
}

// 获取管理员列表
const fetchAdminList = async () => {
  loading.value = true
  try {
    // 支持条件查询时优先用 searchAdmins，否则用 getAllAdmins
    const params = {
      page: pagination.currentPage,
      size: pagination.pageSize,
      username: searchForm.username || undefined,
      email: searchForm.email || undefined,
      role: searchForm.role || undefined
    }
    let response
    if (searchForm.username || searchForm.email || searchForm.role) {
      response = await searchAdmins(params)
    } else {
      response = await getAllAdmins(params)
    }
    if (response.success) {
      adminList.value = response.data
      pagination.total = response.data.length
      // update horizontal scroll state after table data changes
      setTimeout(() => updateHScroll(), 50)
    } else {
      ElMessage.error(response.msg || '获取管理员列表失败')
    }
  } catch (error) {
    ElMessage.error('网络异常，请稍后重试')
    console.error('获取管理员列表失败：', error)
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  pagination.currentPage = 1
  fetchAdminList()
}

// 重置搜索
const handleReset = () => {
  searchForm.username = ''
  searchForm.email = ''
  searchForm.role = ''
  pagination.currentPage = 1
  fetchAdminList()
}

// 弹窗相关
const dialogVisible = ref(false)
const dialogMode = ref('add') // 'add' or 'edit'
const editId = ref(null)
const editData = ref(null)

// 修改密码弹窗
const pwdDialogVisible = ref(false)
const pwdEditId = ref(null)

// Horizontal scroll controls
const tableScroll = ref(null)
const hScrollPercent = ref(0)
const showHScroll = ref(false)

const updateHScroll = () => {
  const el = tableScroll.value
  if (!el) return
  const maxScroll = el.scrollWidth - el.clientWidth
  if (maxScroll > 0) {
    showHScroll.value = true
    hScrollPercent.value = Math.round((el.scrollLeft / maxScroll) * 100)
  } else {
    showHScroll.value = false
    hScrollPercent.value = 0
  }
}

const onTableScroll = () => {
  updateHScroll()
}

const onSliderInput = (e) => {
  const el = tableScroll.value
  if (!el) return
  const maxScroll = el.scrollWidth - el.clientWidth
  const percent = Number(e.target.value || 0)
  el.scrollLeft = Math.round((percent / 100) * maxScroll)
  hScrollPercent.value = percent
}

// 新增管理员
const handleAdd = () => {
  dialogMode.value = 'add'
  editId.value = null
  editData.value = null
  dialogVisible.value = true
}

// 编辑管理员
const handleEdit = async (row) => {
  dialogMode.value = 'edit'
  editId.value = row.uid
  try {
    const res = await getAdminById(row.uid)
    if (res.success) {
      editData.value = res.data
      dialogVisible.value = true
    } else {
      ElMessage.error(res.msg || '获取管理员信息失败')
    }
  } catch (e) {
    ElMessage.error('网络异常，获取管理员信息失败')
  }
}

// 打开修改密码弹窗
const handleChangePassword = (row) => {
  pwdEditId.value = row.uid
  pwdDialogVisible.value = true
}

// 密码弹窗提交后处理（上层接收 PasswordDialog 的 success 事件）
const handlePasswordSuccess = async (payload) => {
  // payload: { password }
  try {
    const res = await changeAdminPassword(pwdEditId.value, payload.password)
    if (res.success) {
      ElMessage.success('密码修改成功')
      pwdDialogVisible.value = false
    } else {
      ElMessage.error(res.msg || '修改密码失败')
    }
  } catch (e) {
    ElMessage.error('网络异常，请稍后重试')
  }
}

// 弹窗提交成功回调
const handleDialogSuccess = async (formData) => {
  try {
    let res
    if (dialogMode.value === 'add') {
      res = await addAdmin(formData)
    } else {
      res = await updateAdmin(editId.value, formData)
    }
    if (res.success) {
      ElMessage.success(dialogMode.value === 'add' ? '添加成功' : '编辑成功')
      dialogVisible.value = false
      fetchAdminList()
    } else {
      // 后端校验失败，弹窗内提示
      ElMessage.error(res.msg || '操作失败')
    }
  } catch (e) {
    ElMessage.error('网络异常，请稍后重试')
  }
}

// 删除管理员
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm('确定要删除该管理员吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    await deleteAdmin(row.uid)
    ElMessage.success('删除成功')
    fetchAdminList()
  } catch (error) {
    if (error === 'cancel') {
      ElMessage.info('已取消删除')
    } else {
      ElMessage.error('删除失败，请稍后重试')
      console.error('删除管理员失败：', error)
    }
  }
}

// 每页条数改变
const handleSizeChange = (val) => {
  pagination.pageSize = val
  pagination.currentPage = 1
  fetchAdminList()
}

// 当前页改变
const handleCurrentChange = (val) => {
  pagination.currentPage = val
  fetchAdminList()
}

// 页面挂载时获取管理员列表
onMounted(() => {
  fetchAdminList()
  // attach scroll listener if wrapper exists later after render
  // use a small timeout to bind (table may render asynchronously)
  setTimeout(() => {
    if (tableScroll.value) {
      tableScroll.value.addEventListener('scroll', onTableScroll, { passive: true })
      updateHScroll()
    }
  }, 100)
  window.addEventListener('resize', updateHScroll)
})

onBeforeUnmount(() => {
  if (tableScroll.value) tableScroll.value.removeEventListener('scroll', onTableScroll)
  window.removeEventListener('resize', updateHScroll)
})
</script>